package com.semidata.rtd.core.log;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;

import com.semidata.rtd.core.log.LogBlockHandler;
import com.semidata.rtd.core.log.LogEvent;
import com.semidata.rtd.core.log.LogEventHandler;

public class ErrorLogHandler extends LogEventHandler {
    
    public static final String NAME = "ERROR";

    public ErrorLogHandler(LogBlockHandler handler) {
        super(handler);
    }

    @Override
    protected File getLogFile(LogEvent event, String root) {

        if (event.getType() != NAME)
            return null;

        Date date = new Date(event.getTimestamp());
        String fileName = new SimpleDateFormat("yyyyMMdd").format(date);
        fileName = fileName.concat(".log");
       
        File dir = new File(root, event.getType().toLowerCase());
        File file = new File(dir, fileName);
        if (file.exists()) {
            if (!file.isFile() || !file.canWrite())
                return null;
        }
        return file;
    }

    @Override
    protected String getLogContent(LogEvent event) {
        if (event.getType() != NAME)
            return null;
        
        StringBuffer sb = new StringBuffer();
        Date date = new Date(event.getTimestamp());
        sb.append('[');
        sb.append(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS").format(date));
        sb.append(']');
        sb.append(' ');
        sb.append(event.getContent());
        if (!event.getContent().endsWith("\n"))
            sb.append('\n');
        return sb.toString();
    }

    @Override
    protected boolean verify(String root) {
        File dir = new File(root, NAME.toLowerCase());
        if (dir.exists()) {
            if (!dir.isDirectory() || !dir.canExecute() || !dir.canWrite())
                return false;
        } else {
            if (!dir.mkdirs())
                return false;
        }
        return true;
    }

}
